package sy.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import sy.model.Tappinfo;
import sy.pageModel.DataGrid;
import sy.pageModel.Json;
import sy.pageModel.PageHelper;
import sy.pageModel.SessionInfo;
import sy.service.AppinfoServiceI;
import sy.util.ConfigUtil;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/appController")
public class AppController extends BaseController  {

    @Autowired
    private AppinfoServiceI appinfoService;

    //获取app列表
    @RequestMapping("/getapplist")
    @ResponseBody
    public String getapplist(HttpSession session,HttpServletRequest request) {
        JSONObject jsobj = new JSONObject();

        String maxsize=request.getParameter("maxsize");
        String curentpage=request.getParameter("curentpage");
        List<Tappinfo> list=appinfoService.getTapps(maxsize,curentpage);


        if(list.size()>0){
            String path=null;
            for(Tappinfo tappinfo:list){
                path=tappinfo.getAppAddress();
                if(path!=null&&!"".equals(path)){
                    path=path.substring(path.indexOf("/")+1);
                    tappinfo.setAppAddress("/dowloadController/dowload?dowloadpath="+path);
                }
//                if(tappinfo.getDescription()!=null){
//                    String subStr = tappinfo.getDescription().replaceAll("\\&[a-zA-Z]{0,9};", "").replaceAll("<[^>]*>", "");
//                    tappinfo.setDetailaddress(subStr);
//                }

            }

            jsobj.put("status", "1");
            jsobj.put("msg",list);
        }else{
            jsobj.put("status", "0");
            jsobj.put("msg","没有数据");
        }

        return jsobj.toJSONString();
    }


    @RequestMapping("/editPage")
    public String editPage(HttpServletRequest request, String id) {
        Tappinfo u = appinfoService.get(id);
        request.setAttribute("appinfo", u);
        return "/adminapp/appeditor";
    }

    @RequestMapping("/delete")
    @ResponseBody
    public Json delete(String id, HttpSession session,HttpServletRequest request) {
        Json j = new Json();
        if (id != null) {
            Tappinfo tappinfo=	appinfoService.get(id);
            appinfoService.delete(id);

            //删除文件
            deleteapp(tappinfo.getAppname(),request,"appupload");

        }
        j.setMsg("删除成功！");
        j.setSuccess(true);
        return j;
    }

    /**
     * 批量删除
     *
     * @param ids
     *            ('0','1','2')
     * @return
     */
    @RequestMapping("/batchDelete")
    @ResponseBody
    public Json batchDelete(String ids, HttpSession session,HttpServletRequest request) {
        Json j = new Json();
        if (ids != null && ids.length() > 0) {
            for (String id : ids.split(",")) {
                if (id != null) {
                    this.delete(id, session,request);
                }
            }
        }
        j.setMsg("批量删除成功！");
        j.setSuccess(true);
        return j;
    }
    @RequestMapping("/edit")
    @ResponseBody
    public String edit(HttpServletRequest request,HttpServletResponse response,HttpSession session) {
        response.setCharacterEncoding("utf-8");
        Tappinfo  tappinfo=new Tappinfo();
        tappinfo.setDescription(request.getParameter("description"));
        tappinfo.setVersion(request.getParameter("version"));
        tappinfo.setAppname(request.getParameter("appname"));
        tappinfo.setIntegral(request.getParameter("integral"));
        tappinfo.setId(request.getParameter("id"));

        JSONObject jsobj = new JSONObject();
        SessionInfo sessionInfo = (SessionInfo) session.getAttribute(ConfigUtil.getSessionInfoName());

        ServletContext context=request.getSession().getServletContext();
        String realpath = context.getRealPath("/appupload");
        File filelocal = new File(realpath);
        if(!filelocal.exists()) filelocal.mkdirs();

        if(sessionInfo == null){
            jsobj.put("status", -1);
            jsobj.put("msg", "登录超时");
        }else{
            try {
                Tappinfo localappinfo=appinfoService.get(tappinfo.getId());

                localappinfo.setAppname(tappinfo.getAppname());
                localappinfo.setDescription(tappinfo.getDescription());
                localappinfo.setIntegral(tappinfo.getIntegral());

                //生成下载文件
                //String content,String appname ,String filesize,String version,String code,String doloadpath
                String htmlpage=getHead(tappinfo.getDescription().trim(),tappinfo.getAppname(),tappinfo.getAppsize(),tappinfo.getVersion(),tappinfo.getIntegral(),tappinfo.getAppAddress());


                if(!filelocal.exists()) filelocal.mkdirs();

                String filenameapp=UUID.randomUUID().toString();
                FileOutputStream out = new FileOutputStream(filelocal.getAbsolutePath()+"\\"+filenameapp+".html");

                out.write(htmlpage.getBytes());
                out.close();
                //设置详细页

                localappinfo.setDetailaddress("/appupload/"+filenameapp+".html");

                appinfoService.update(localappinfo);

                jsobj.put("status", 1);
                jsobj.put("msg", "更新成功");

            } catch (Exception e) {
                e.printStackTrace();
                jsobj.put("status", 0);
                jsobj.put("msg", "更新失败");
            }
        }
        return jsobj.toJSONString();
    }
    /**
     * 获取用户数据表格
     *
     * @param user
     * @return
     */
    @RequestMapping("/dataGrid")
    @ResponseBody
    public DataGrid dataGrid(Tappinfo tappinfo, PageHelper ph) {
        return appinfoService.dataGrid(tappinfo, ph);
    }


    @RequestMapping(method=RequestMethod.POST, value="/appuploadssss")
    @ResponseBody

    public  Json appupload(HttpServletResponse response,HttpServletRequest request, @RequestParam MultipartFile[] files)throws Exception{


        response.setContentType("text/html");
        Json jsobj = new Json();

        String appname=request.getParameter("appname");
        String imageurl=request.getParameter("imageurl");

        appname=new String(appname.getBytes("ISO-8859-1"),"UTF-8");

        String integral=request.getParameter("integral");
        String description=request.getParameter("description").trim();

        description=new String(description.getBytes("ISO-8859-1"),"UTF-8");

        if("".equals(appname)||"".equals(integral)){

            jsobj.setSuccess(false);
            return jsobj;
        }


        ServletContext context=request.getSession().getServletContext();
        String realpath = context.getRealPath("/appupload");
        File filelocal = new File(realpath);
        if(!filelocal.exists()) filelocal.mkdirs();
        String filename="error";
        String hz=null;
        String uploadImageFileName=files[0].getOriginalFilename();


        if(!"".equals(uploadImageFileName)&&uploadImageFileName!=null){
            hz=uploadImageFileName.substring(uploadImageFileName.lastIndexOf(".")+1);
        }

        filename=UUID.randomUUID().toString()+"."+hz;

        try {
            //保存文件
            SaveFileFromInputStream(files[0].getInputStream(),filelocal.getAbsolutePath(),filename);

            //添加app到数据库
            Tappinfo tappinfo=new Tappinfo();
            tappinfo.setAppAddress("/appupload/"+filename);
            tappinfo.setAppname(appname);
            tappinfo.setDescription(description);
            tappinfo.setIntegral(integral);
            tappinfo.setCreatetime(new Date().getTime()+"");
            tappinfo.setImageurl(imageurl);

            appinfoService.add(tappinfo);
            jsobj.setMsg("发布成功！");
            jsobj.setSuccess(true);
        } catch (Exception e) {
            jsobj.setMsg("发布失败！");
            jsobj.setSuccess(false);
            e.printStackTrace();
        }

        return jsobj;

    }

    @RequestMapping(value = "/appupload", method = RequestMethod.POST)
    public Json uploadOrder(MultipartHttpServletRequest multipartRequest,
                            HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("text/html;charset=UTF-8");
        String result = "";
        Json jsobj = new Json();

        String appname=request.getParameter("appname");
        String version=request.getParameter("version");

        appname=new String(appname.getBytes("ISO-8859-1"),"UTF-8");

        String integral=request.getParameter("integral");
        String description=request.getParameter("description");

        description=new String(description.getBytes("ISO-8859-1"),"UTF-8");

        if("".equals(appname)||"".equals(integral)){

            jsobj.setSuccess(false);
            return jsobj;
        }
        ServletContext context=request.getSession().getServletContext();
        String realpath = context.getRealPath("/appupload");
        File filelocal = new File(realpath);
        if(!filelocal.exists()) filelocal.mkdirs();
        String filename="error";
        String hz=null;
        String uploadImageFileName=null;
        //添加app到数据库
        Tappinfo tappinfo=new Tappinfo();
        try {
            for (Iterator it = multipartRequest.getFileNames(); it.hasNext();) {
                String key = (String) it.next();
                MultipartFile orderFile = multipartRequest.getFile(key);
                if (orderFile.getOriginalFilename().length() > 0) {

                    uploadImageFileName=orderFile.getOriginalFilename();
                    if(!"".equals(uploadImageFileName)&&uploadImageFileName!=null){
                        hz=uploadImageFileName.substring(uploadImageFileName.lastIndexOf(".")+1);
                    }
                    filename=UUID.randomUUID().toString()+"."+hz;

                    FileUtils.copyInputStreamToFile(orderFile.getInputStream(), new File(realpath, filename));

                    if("appfile".equals(key)){
                        long size=orderFile.getSize()/1024/1024;
                        tappinfo.setAppsize(size+"");
                        tappinfo.setAppAddress("/appupload/"+filename);
                    }else{
                        tappinfo.setImageurl("/appupload/"+filename);
                    }

                }
            }


            tappinfo.setAppname(appname);
            tappinfo.setDescription(description);
            tappinfo.setIntegral(integral);
            tappinfo.setCreatetime(new Date().getTime()+"");
            tappinfo.setVersion(version);
            //生成下载文件
            //String content,String appname ,String filesize,String version,String code,String doloadpath
            String htmlpage=getHead(tappinfo.getDescription(),tappinfo.getAppname(),tappinfo.getAppsize(),tappinfo.getVersion(),tappinfo.getIntegral(),tappinfo.getAppAddress());


            if(!filelocal.exists()) filelocal.mkdirs();

            String filenameapp=UUID.randomUUID().toString();
            FileOutputStream out = new FileOutputStream(filelocal.getAbsolutePath()+"\\"+filenameapp+".html");

            out.write(htmlpage.getBytes());
            out.close();
            //设置详细页

            tappinfo.setDetailaddress("/appupload/"+filenameapp+".html");

            appinfoService.add(tappinfo);
            jsobj.setMsg("发布成功！");
            jsobj.setSuccess(true);

        } catch (Exception e) {
            jsobj.setMsg("发布失败！");
            jsobj.setSuccess(false);
            e.printStackTrace();
        }

        return jsobj;
    }

    public  String getHead(String content,String appname ,String filesize,String version,String code,String doloadpath){
        String head="<!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'>" +
                "<html>" +
                "<head>" +
                "  <meta http-equiv='Content-Type' content='text/html;' charset='gbk' />" +
                "  <meta name='viewport' content='initial-scale=1.0, user-scalable=no'>" +
                "  <meta name='apple-mobile-web-app-capable' content='yes'>" +
                "  <meta name='apple-mobile-web-app-status-bar-style' content='black'>" +
                "  <title></title>" +
                "<link href='/css/playground.css' media='all' rel='stylesheet' type='text/css' />" +
                "    <style type='text/css' >" +
                "        *{" +
                "            padding: 0px;" +
                "            margin: 0px;" +
                "            " +
                "        }" +
                "        ul,li{" +
                "            list-style: none;;" +
                "        }" +
                "        .head ul li{display: block;float: left;height: 80px;" +
                "            width: 50%;}" +
                "        .root{" +
                "            display: block;" +
                "            width: 100%;" +
                "            height: 80px;}" +
                "        .content{" +
                "            width: 100%;height: 100%;" +
                "            overflow: hidden;clear: left}" +
                "        .left ol li{display: block;float: left;}" +
                "    </style>" +
                "" +
                "    <style type='text/css'>" +
                "        /* Place all stylesheet code here */" +
                "        body { text-shadow: 0 1px 1px rgba(0,0,0,.5); }" +
                "" +
                "" +
                "        @-webkit-keyframes bigAssButtonPulse {" +
                "            from { background-color: #749a02; -webkit-box-shadow: 0 0 25px #333; }" +
                "            50% { background-color: #91bd09; -webkit-box-shadow: 0 0 50px #91bd09; }" +
                "            to { background-color: #749a02; -webkit-box-shadow: 0 0 25px #333; }" +
                "        }" +
                "" +
                "        @-webkit-keyframes greenPulse {" +
                "            from { background-color: #749a02; -webkit-box-shadow: 0 0 9px #333; }" +
                "            50% { background-color: #91bd09; -webkit-box-shadow: 0 0 18px #91bd09; }" +
                "            to { background-color: #749a02; -webkit-box-shadow: 0 0 9px #333; }" +
                "        }" +
                "" +
                "        @-webkit-keyframes bluePulse {" +
                "            from { background-color: #007d9a; -webkit-box-shadow: 0 0 9px #333; }" +
                "            50% { background-color: #2daebf; -webkit-box-shadow: 0 0 18px #2daebf; }" +
                "            to { background-color: #007d9a; -webkit-box-shadow: 0 0 9px #333; }" +
                "        }" +
                "" +
                "        @-webkit-keyframes redPulse {" +
                "            from { background-color: #bc330d; -webkit-box-shadow: 0 0 9px #333; }" +
                "            50% { background-color: #e33100; -webkit-box-shadow: 0 0 18px #e33100; }" +
                "            to { background-color: #bc330d; -webkit-box-shadow: 0 0 9px #333; }" +
                "        }" +
                "" +
                "        @-webkit-keyframes magentaPulse {" +
                "            from { background-color: #630030; -webkit-box-shadow: 0 0 9px #333; }" +
                "            50% { background-color: #a9014b; -webkit-box-shadow: 0 0 18px #a9014b; }" +
                "            to { background-color: #630030; -webkit-box-shadow: 0 0 9px #333; }" +
                "        }" +
                "" +
                "        @-webkit-keyframes orangePulse {" +
                "            from { background-color: #d45500; -webkit-box-shadow: 0 0 9px #333; }" +
                "            50% { background-color: #ff5c00; -webkit-box-shadow: 0 0 18px #ff5c00; }" +
                "            to { background-color: #d45500; -webkit-box-shadow: 0 0 9px #333; }" +
                "        }" +
                "" +
                "        @-webkit-keyframes orangellowPulse {" +
                "            from { background-color: #fc9200; -webkit-box-shadow: 0 0 9px #333; }" +
                "            50% { background-color: #ffb515; -webkit-box-shadow: 0 0 18px #ffb515; }" +
                "            to { background-color: #fc9200; -webkit-box-shadow: 0 0 9px #333; }" +
                "        }" +
                "" +
                "        a.button {" +
                "            -webkit-animation-duration: 2s;" +
                "            -webkit-animation-iteration-count: infinite;" +
                "        }" +
                "" +
                "        .green.button { -webkit-animation-name: greenPulse; -webkit-animation-duration: 3s; }" +
                "        .blue.button { -webkit-animation-name: bluePulse; -webkit-animation-duration: 4s; }" +
                "        .red.button { -webkit-animation-name: redPulse; -webkit-animation-duration: 1s; }" +
                "        .magenta.button { -webkit-animation-name: magentaPulse; -webkit-animation-duration: 2s; }" +
                "        .orange.button { -webkit-animation-name: orangePulse; -webkit-animation-duration: 3s; }" +
                "        .orangellow.button { -webkit-animation-name: orangellowPulse; -webkit-animation-duration: 5s; }" +
                "" +
                "        .wall-of-buttons { width: 100%; height: 180px; text-align: center; }" +
                "        .wall-of-buttons a.button { display: inline-block; margin: 0 10px 9px 0; }" +
                "    </style>"+
                " </head><body> ";


        head+=" <div class='head' ><ul> <li class='left'> <ol >";
        head+="<li style='display: block;width: 65px;height: 65px;'><img src='/images/apple.png' width='65' height='65'></li>" ;
        head+= "<li style='margin: 5px;'> <dl> <dt style='font-weight: bold;font-size: 18px;'>"+appname+"</dt>" ;
        head+=      "                            <dd style='color: #dcdcdc'>" +
                "                                <p>版本号 "+version+"</p>" +
                "                                <p>大小 "+filesize+"M</p>" +
                "                            </dd>" +
                "                        </dl>" +
                "                    </li>" +
                "                </ol>" +
                "            </li>" +
                "            <li class='right' style='position:relative;'>" +
                "                <dl style='width:100px;position: absolute;right: 0px;border-left: 1px solid #d3d3d3;height: 70px;margin-top: 5px;padding-left: 5px;'>" +
                "                    <dt>送"+code+"金币</dt>" +
                "                    <dd>  <a class='large red button' href='"+doloadpath+"'>下载</a></dd>" +
                "                </dl>" +
                "            </li>" +
                "        </ul>" +
                "    </div>" +
                "    <div class='content' style='border-top: 1px solid #d3d3d3;'>" +
                content +
                "    </div>" +
                "    <div class='root' style='text-align: center;border-top: 1px solid #d3d3d3;padding-top: 10px;'>" +
                "        <a class='large orange button' href='"+doloadpath+"'>立即下载安装>></a>" +
                "    </div>";


        String end="</body></html>";
        return head+=end;
    }

    //保存文件
    private File saveFileFromInputStream(InputStream stream, String path,	String filename) throws IOException {
        File file = new File(path + "/" + filename);
        FileOutputStream fs = new FileOutputStream(file);
        byte[] buffer = new byte[1024 * 1024];
        int bytesum = 0;
        int byteread = 0;
        while ((byteread = stream.read(buffer)) != -1) {
            bytesum += byteread;
            fs.write(buffer, 0, byteread);
            fs.flush();
        }
        fs.close();
        stream.close();
        return file;
    }

    public void SaveFileFromInputStream(InputStream stream,String path,String savefile) throws IOException
    {
        FileOutputStream fs=new FileOutputStream( path + "/"+ savefile);

        byte[] buffer =new byte[1024*1024];
        int bytesum = 0;
        int byteread = 0;
        while ((byteread=stream.read(buffer))!=-1)
        {
            bytesum+=byteread;
            fs.write(buffer,0,byteread);
            fs.flush();
        }
        fs.close();
        stream.close();
    }


    public void deleteapp(String  appname,HttpServletRequest request,String dir){
        try{
            ServletContext context=request.getSession().getServletContext();
            String realpath = context.getRealPath("/"+dir);
            File file = new File(realpath);
            File[] files=file.listFiles();

            for(File f:files){
                if(f.getName().indexOf(appname)>-1){
                    //删除文件
                    f.delete();
                    break;
                }
            }
        } catch (Exception e) {

            e.printStackTrace();
        }


    }

    //获取已经上传的app文件列表
    @ResponseBody
    @RequestMapping("/applist")
    public  void applist(HttpServletRequest request,HttpServletResponse response){
        ServletContext context=request.getSession().getServletContext();
        String realpath = context.getRealPath("/upload");
        File file = new File(realpath);
        File[] appfiles=file.listFiles();

        JSONArray array=new JSONArray();
        JSONObject jsonObject=null;
        String path = request.getContextPath();
        String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

        if(appfiles!=null){
            for(int i=0;i<appfiles.length;i++){
                jsonObject=new JSONObject();
                jsonObject.put("filename", appfiles[i].getName());
                jsonObject.put("filepath", basePath+"upload/"+appfiles[i].getName());

                array.add(jsonObject);
            }
        }

        PrintWriter out;
        try {
            out = (PrintWriter)response.getWriter();
            out.print(array);
            out.flush();
            out.close();

        } catch (IOException e) {
            e.printStackTrace();
        }


    }


}
